package multiplayer.lan;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class BroadcastListener implements Runnable {
	private static int DEFAULT_PORT=7650;
	private ServersOnAir soa;
	private boolean terminate=false;
	DatagramSocket s;
	public BroadcastListener(ServersOnAir soa) {
		this.soa=soa;
	}
	public void setTerminate(boolean terminate) {
		this.terminate = terminate;
	}
	@Override
	public void run() {
		try {
			
			s = new DatagramSocket(DEFAULT_PORT);
			while (!terminate) {
				//Preparazione delle informazioni da ricevere
				byte[] buf = new byte[65536];
				
				DatagramPacket recv = new DatagramPacket(buf, buf.length);
				s.receive(recv);

				//Informazioni sul Client che ha effettuato la chiamata
				InetAddress address = recv.getAddress();
				String client = address.getHostAddress();

				//Messaggio ricevuto dal Client
				String messaggio = (new String(recv.getData()).trim());
				System.out.println(messaggio);
				String[] splitted = messaggio.split("-");
				if(splitted.length>1){
					if(splitted[0].equals("chess")){
						soa.addServer(client, splitted[1],Integer.parseInt(splitted[2]));
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			s.close();
		}
		
	}
	public boolean isTerminate() {
		return terminate;
	}


}
